
////////////////////////////////////////////////////////////////////////////////
//
// RSum.java
//
// Copyright © (C) 2010
// 
// Emory Hughes Merryman, III
// emory.merryman@gmail.com
// 
// All Rights Reserved
// 
// This file is part of Interworks.
// 
// Interworks is free software: you can 
// redistribute it and/or modify it under 
// the terms of the GNU General Public 
// License as published by the Free 
// Software Foundation, either version 3 
// of the License, or (at your option) any 
// later version.
// 
// This program is distributed in the hope 
// that it will be useful, but WITHOUT 
// ANY WARRANTY; without even the 
// implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR 
// PURPOSE.  See the GNU General Public 
// License for more details.
//
// You should have received a copy of the 
// GNU General Public License along with 
// this program.  If not, see 
// <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////

/**
 * This is a package for research into R.
 **/
package com . superiorglobalbusiness . researchr ;

import java . io . OutputStream ;
import java . io . OutputStreamWriter ;
import java . io . Writer ;
import
    org . springframework . beans . factory . annotation .
    Autowired ;
import org . springframework . context . annotation . Scope ;

import java . io . IOException ;

@ Scope ( "prototype" )
    final class RSum extends Sum
    {
	private static final int A_WHILE = 1000 ;

	private Process process_ ;

	private OutputStream output_ ;

	private Writer writer_ ;

	@ Autowired
	    RSum ( final int numberOfTrials , final int sizeOfArray )
	{
	    super ( "R Interpreted" , numberOfTrials , sizeOfArray ) ;
	}

	void setUp ( ) throws IOException
	{
	    process_ = Runtime . getRuntime ( ) . exec ( "R" ) ;
	    output_ = process_ . getOutputStream ( ) ;
	    writer_ = new OutputStreamWriter ( output_ ) ;
	    writer_ . write
		(
		 "simpleSum "
		 +
		 "<- function function ( x ) { "
		 +
		 "sum <- 0 ; "
		 +
		 "for ( e in x ) { sum <- sum + e ; } "
		 +
		 "sum ; "
		 +
		 "}"
		 ) ;
	    int numberOfTrials = this . getNumberOfTrials ( ) ;
	    writer_ . write ( "x <- seq ( 0 , 0 , length.out=" ) ;
	    writer_ . write ( Integer . toString ( numberOfTrials ) ) ;
	    writer_ . write ( " )" ) ;
	    writer_ . flush ( ) ;
	}

	void tearDown ( ) throws IOException , InterruptedException
	{
	    writer_ . write ( "q();" ) ;
	    writer_ . flush ( ) ;
	    Thread . sleep ( A_WHILE ) ;
	    writer_ . write ( "n" ) ;
	    writer_ . flush ( ) ;
	    writer_ . close ( ) ;
	    output_ . close ( ) ;
	    writer_ = null ;
	    output_ = null ;
	    process_ = null ;
	}

	public Void call ( )
	{
	
	    return ( null ) ;
	}
    }
